<?php
/**
 * Created by PhpStorm.
 * User: sen
 * Date: 16/7/26
 * Time: 下午7:33
 */
use app\assets\AuctionListAsset;
use yii\helpers\Html;
use yii\widgets\ActiveForm;

AuctionListAsset::register($this);
?>
<div id="toolbar">
    <button id="remove" class="btn btn-danger" disabled>
        <i class="glyphicon glyphicon-remove"></i> 批量删除
    </button>
    <button id="addBannerBtn" class="btn btn-primary" style="margin-left: 10px;">
        <i class="glyphicon glyphicon-plus"></i> 添加
    </button>
</div>

<table id="table">
</table>



<!--删除Modal-->
<div class="modal fade" id="removeModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <!--记录-->
                <span id="remove_id" hidden></span>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">确定要删除该轮播图吗？</h4>
            </div>
            <div class="modal-body">
                <p style="color: #FF3333">删除后将无法恢复,请谨慎操作。</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary"  data-dismiss="modal" id="remove_btn">确定</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->


<!--上传图片的Modal-->
<div class="modal fade" id="uploadModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">请上传图片文件(建议上传宽图，微信端展示更加美观)</h4>
            </div>
            <div class="modal-body">
                <p class="help-block">格式为png,jpg,jpeg格式的图片文件</p>

                <input type="file" accept="image/jpg,image/jpeg,image/png" id="upload-file" name="upload-file" onchange="thumbImage(this)" style="display: none">
                <button class="select-img" onclick="upload(this)"  style="width: 80px;height: 30px;border-radius: 3px;border: 1px solid #ccc;background-color: #fff">选择图片</button>
                <div class="pic-area" >
                    <img class="pic-area-img" id="pic-area-img" >
                </div>
                <div>
                    <input type="hidden" id="x" name="x">
                    <input type="hidden" id="y" name="y">
                    <input type="hidden" id="w" name="w">
                    <input type="hidden" id="h" name="h">
                    <input type="hidden" id="bili" name="bili">
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="submit" class="btn btn-primary" data-dismiss="modal" onclick="uploadImage(this)">上传</button>
            </div>


        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<!--修改的Modal-->
<div class="modal fade" id="editModal">
    <div class="modal-dialog modal-lg" style="width: 860px">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">编辑跳转详情页面</h4>
                <p style="display: none" id="banner_id_p"></p>
            <div class="modal-body" >
<!--                <div class="col-md-12 editorDiv">-->
                        <script type="text/plain" id="myEditor" style="width:800px;height:500px;">
                        </script>
<!--                 </div>-->

                <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="editSaveBtn">保存</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->


<script>



    $('#upload-file').attr('autocomplete','off');

    //初始化表格设置
    $('#table').bootstrapTable({
        height: 800,//高度
        toolbar: '#toolbar',        //工具按钮用哪个容器
        clickToSelect: false,//点击行即可选中单选/复选框
        singleSelect: false,//复选框只能选择一条记录
        search: false,//是否显示右上角的搜索框
        striped: true,      //是否显示行间隔色
        cache: false,            //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,     //是否显示分页（*）
        sortable: false,           //是否启用排序
        sortOrder: "asc",          //排序方式
        sidePagination: "server", //服务端处理分页
        method: 'get',      //请求方式（*）
        pageNumber:1,      //初始化加载第一页，默认第一页
        pageSize: 10,      //每页的记录行数（*）
        pageList: [10, 20, 50, 100],  //可供选择的每页的行数（*）
        cardView: false,          //是否显示详细视图
        uniqueId:'banner_id',
        url:"table-data",

        columns: [{
            field: 'state',
            checkbox: true,
            align: 'center',
            width:'5%',
            valign: 'middle'
        },{
            field: '',
            align: 'center',
            title: '轮播图',
            width:'50%',
            valign: 'middle',
            formatter:function(value,row,index){
                var a = '<img src="'+row.pic_url+'"'+'alt="轮播图片" style="width: 100px;height: 80px">';
                return a;}
        },{
            field: 'create_time',
            align: 'center',
            valign: 'middle',
            width:'25%',
            title: '上传时间'
        },{
            field: 'operate',
            align: 'center',
            valign: 'middle',
            width:'20%',
            title: '操作',
            formatter:function(value,row,index){
                var a = '<a href="#" mce_href="#" onclick="onEditClick(\''+ row.banner_id+'\',\'' +row.content+ '\')">编辑</a> ';

                var b = '<a href="#" mce_href="#" onclick="onRemoveClick(\''+ row.banner_id + '\')">删除</a> ';

                return a+b;}
        }]
    });

    //复选框点击事件
    $('#table').on('check.bs.table uncheck.bs.table ' +
        'check-all.bs.table uncheck-all.bs.table', function () {
        $('#remove').prop('disabled', !$('#table').bootstrapTable('getSelections').length);
        selections = getIdSelections();

    });

    //获取选择的合集
    function getIdSelections() {
        return $.map($('#table').bootstrapTable('getSelections'), function (row) {
            return row.banner_id;
        });
    }

    //批量删除操作
    $('#remove').click(function () {
        var ids = getIdSelections();
        console.log('ids:'+ids);

        $.ajax({
            url: "remove-banner",
            data:{"banner_id":ids},
            dataType: "json",
            success: function (data) {

                $('#table').bootstrapTable('remove', {
                    field: 'banner_id',
                    values: ids
                });
                $('#remove').prop('disabled', true);
                alert('批量删除成功');
            }
        });

    });


    //点击表格中删除a标签
    function onRemoveClick(banner_id){

        $('#remove_id').html(banner_id);
        $('#removeModal').modal();

    }

    $('#remove_btn').click(function(){

        $.ajax({
            url: "remove-banner",
            data: {"banner_id": $('#remove_id').html()},
            dataType: "json",
            success: function (data) {
                console.log(data);
                $('#removeModal').modal('hide');
                $('#table').bootstrapTable('removeByUniqueId', $('#remove_id').html());
                alert('删除成功');
            }
        });


    });

    //点击编辑按钮
    function onEditClick(banner_id,content) {

        $('#banner_id_p').html(banner_id);

        UM.getEditor('myEditor').setContent(content,false,false);

        $('#editModal').modal();


    }

    //获取输入内容
    function getContent() {
        return UM.getEditor('myEditor').getContent();
    }


    $(function() {


        //实例化富文本编辑器
        var um = UM.getEditor('myEditor');
//        console.log($('#editorDiv').width());
//        UM.getEditor('myEditor').setWidth($('#editorDiv').width());

        $('#addBannerBtn').click(function(){

            $.ajax({
                url: "get-banner-num",
                dataType: "json",
                success: function (data) {

                    if(data<6){
                        $('#uploadModal').modal();
                        if ($('.jcrop-holder').length){
                            $('.pic-area').empty();
                            $('.pic-area').prepend('<img class="pic-area-img" id="pic-area-img" >');
                        }
                    }else{
                        alert('最多只有6张轮播图，请删除一些已有的轮播图再重试！');
                    }

                }
            });


        });

        $('#editSaveBtn').click(function(){

            var banner_id = $('#banner_id_p').html();
            var content = getContent();

            $.ajax({
                type:'post',
                url: "save-banner",
                data: {"banner_id": banner_id,"content":content},
                dataType: "json",
                success: function (data) {

                    console.log(data);
                    if(data==1){

                    }else{
                        alert('未做任何修改');
                    }

                    $('#editModal').modal('hide');

                    $('#table').bootstrapTable('refresh');


                }
            });


        });

    });


    //点击图片来选择上传的图片
    function upload(button){
        $("#upload-file").val('');
        document.getElementById('upload-file').click();

    }


    //图片缩略图处理
    function thumbImage(input){
        //设置宽高比
        var w = 5;
        var h = 2;
        var jcrop_api;
        //再次点击上传时清除之前的截图操作
        if ($('.jcrop-holder').length){
            $('.pic-area').empty();
            $('.pic-area').prepend('<img class="pic-area-img" id="pic-area-img" >');
        }
        if (typeof (FileReader) != "undefined") {
            var regex = /(.jpg|.jpeg|.png)$/;
            $($(input)[0].files).each(function () {
                var file = $(this);
                if (regex.test(file[0].name.toLowerCase())) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
//                        var img = $(input).prev();
                        var img = $('#pic-area-img');
                        $(img).attr('src',e.target.result);
                        var realWidth;//真实的宽度
                        var realHeight;//真实的高度
                        //这里做下说明，$("<img/>")这里是创建一个临时的img标签，类似js创建一个new Image()对象！
                        $("<img/>").attr("src", $(img).attr('src')).load(function() {
                            /*
                             如果要获取图片的真实的宽度和高度有三点必须注意
                             1、需要创建一个image对象：如这里的$("<img/>")
                             2、指定图片的src路径
                             3、一定要在图片加载完成后执行如.load()函数里执行
                             */
                            realWidth = this.width;
                            realHeight = this.height;
                            var width = $('.pic-area').css('width').split('p')[0];
                            var height = $('.pic-area').css('height').split('p')[0];
//                            console.log(realWidth,realHeight,width,height)
                            if(realWidth<width && realHeight<height){
                                $(img).css("width",realWidth+'px').css("height",realHeight+'px');
                            }else{
                                //如果真实的宽高比大于给定的宽高比就按照宽度100%显示
                                if(realWidth/realHeight >= width/height){
                                    $(img).css("width","100%").css("height","auto");
                                }
                                else{//如果小于给定的宽高比按照原尺寸显示
                                    $(img).css("width","auto").css("height","99%");
                                }
                            }
                            var bili=width/realWidth;
                            $("#bili").val(bili);
                            $('#pic-area-img').show();
                            $('#pic-area-img').Jcrop({
                                aspectRatio: w / h,
                                onSelect:uodateCoords
                            },function(){
                                jcrop_api = this;
                                jcrop_api.animateTo([30,30,180,180]);
                            });

                            function uodateCoords(c){
                                $('#x').val(c.x);
                                $('#y').val(c.y);
                                $('#w').val(c.w);
                                $('#h').val(c.h)
//                                console.log(c.x, c.y, c.w, c.h)
                            }
                            var jcropWidth =   $(img).css('width').split('p')[0];
                            var jcropHeight =   $(img).css('height').split('p')[0];
                            var marginLeft = (width-jcropWidth)/2;
                            $('.jcrop-holder').css("margin-left",marginLeft + 'px');
                        });
                    }
                    reader.readAsDataURL(file[0]);
                }else {
                    alert(file[0].name + " is not a valid image file.");
                    return false;
                }
            })
        }else{
            alert("This browser does not support HTML5 FileReader.");
        }
    }
    //ajax 异步上传图片
    function uploadImage(button){
        //定义允许上传的图片格式 在前台就可以直接判断，不合法的格式将不会上传
        //尺寸限制
        var limit = 3 * 1024 * 1024;
        var intputId = 'upload-file';
        var file = $('#'+intputId).get(0).files;

//            $($(button).parent().prev().children()[1]).get(0).files;
        var filetype = ['jpg','jpeg','png','gif'];
        if(file.length){
            fi = file[0]; //得到文件信息
            //判断文件格式是否是图片 如果不是图片则返回false
            var index = fi.name.lastIndexOf('.');
            var fname = [fi.name.substring(0,index),fi.name.substring(index+1)];
            if(filetype.indexOf(fname[1].toLowerCase()) == -1){
                alert('文件格式不支持');
                return ;
            }
            console.log(fname[1].toLowerCase());
            //实例化h5的fileReader
            var fr = new FileReader();
            fr.readAsDataURL(fi); //以base64编码格式读取图片文件
            fr.onload = function(frev){
                pic = frev.target.result; //得到结果数据
                //开始上传之前，预览图片
//                $('#img').attr('src',pic);
                //使用ajax 利用post方式提交数据
                var bili=$('#bili').val();
                var x = $('#x').val()?$('#x').val():30;
                var y= $('#y').val()?$('#y').val():30;
                var width= $('#w').val()?$('#w').val():230/bili;
                var height= $('#h').val()?$('#h').val():100/bili;
                if (width == 0 && height == 0){
                    alert('你还未选择图片');
                    return;
                }
                console.log(x,y,width,height)
                $.post(
                    'upload',
                    {
                        message:pic,
                        filename:fname[0],
                        filetype:fname[1].toLowerCase(),
                        filesize:fi.size,
                        x:x,
                        y:y,
                        width:width,
                        height:height,
                        bili:bili,
                        limit:limit
                    },
                    function(data){
                        data = eval('('+data+')');
                        console.log(data);
                        if(data.code == 1){
                            alert('上传失败');
                        }else if(data.code == 0){
                            alert('上传成功');
                            window.location.reload();
                        }else if(data.code == 2){
                            var msg = data.msg + ',当前图片尺寸为:' + parse(parseInt(data.size)/1000) + 'KB';
                            alert(msg);
                        }
                    }
                    )
                    .fail(function(xhr,status,error){
//                    console.log(xhr,status,error)
                        alert('上传失败')
                    })
            }
        }else
            alert('请选择图片');
    }


</script>